//
//  JCNetWorkTool.swift
//  weibo07777
//
//  Created by mac on 15/12/17.
//  Copyright © 2015年 mac. All rights reserved.
//

import UIKit
import AFNetworking

// 使用枚举来统一管理错误
enum JCNetworkError: Int {
    case emptyAccessToken = -1  // AccessToken没有值
    case emptyUid = -2  // Uid没有值
    
    // 枚举除了有成员之外,还可以有属性和方法
    // 将错误的code和错误的描述关联起来, 使用计算性属性,只有get(只读计算性属性)
    var errorDescription: String {
        get {
            // 判断不同的类型返回不同的错误信息
            switch self {
            case JCNetworkError.emptyAccessToken:
                return "access_token没有值"
            case JCNetworkError.emptyUid:
                return "uid没有值"
            }
        }
    }
    
    // 定义一个方法,返回一个错误,根据枚举类型不一样返回不一样的错误
    func error() -> NSError {
        return NSError(domain: "cn.itcast.error.network", code: self.rawValue, userInfo: ["errorDescription" : self.errorDescription])
    }
}


final class JCNetWorkTool: AFHTTPSessionManager{
    
    
    static var sharedInstance: JCNetWorkTool = {
        
        let tool = JCNetWorkTool(baseURL: NSURL(string: "https://api.weibo.com/"))
        
        tool.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return tool
    }()
    
    // MARK: - Oauth授权
    /// 申请应用时分配的AppKey
    private let client_id = "3473179002"
    /// 申请应用时分配的AppSecret
    private let client_secret = "30088614b9698583210a502040cfded8"
    
    /// 授权回调地址, 一定要一模一样
    let redirect_uri = "http://www.baidu.com/"
    
    
    // 网络请求的枚举
    enum CZNetoworkMethod: String {
        case GET = "GET"
        case POST = "POST"
    }
    
    // 定义类型别名
    typealias NetworkCallback = (result: [String: AnyObject]?, error: NSError?) -> ()
    
    func oauthURL() ->NSURL {
        // GET方式拼接登录界面请求地址
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)"
        return NSURL(string: urlString)!
    }
    // MARK: - 网络工具类加载AccessToken, 只负责加载数据,让别人来处理数据(通过闭包)
    func loadAccessToken(code: String, finished: (result :[String :AnyObject]?,error: NSError?) ->()) {
        // url地址
        let urlString = "oauth2/access_token"
        
        // 请求参数
        let parameters = [
            "client_id": client_id,
            "client_secret": client_secret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirect_uri
        ]
        
        // 发送POST请求
        POST(urlString, parameters: parameters, success: { (_, result) -> Void in
            //            print("result: \(result)")
            // as! 强制转换,f 有风险,如果转换不了,直接崩溃
            // as? 如果能转成功就转换,如果不能转换就返回nil
            finished(result: result as? [String : AnyObject], error: nil)
            }) { (_, error) -> Void in
                //                print("error:\(error)")
                finished(result: nil, error: error)
        }

    }
    
    func loadStatus(finished :(result:[String:AnyObject]?,error:NSError?)->()){
        // 5.1. 判断access_token
        guard let access_token = JCUserAccount.loadAccount()?.access_token else {
            // access_token没有值
            // 5.1.2创建错误返回调用者
            let error = JCNetworkError.emptyAccessToken.error()
            finished(result: nil, error: error)
            return
        }
        
        // 5.2. url地址
        let urlString = "2/statuses/home_timeline.json"
        
        // 5.3. 请求参数
        let parameters = ["access_token": access_token]
        
        // 5.4. 发送请求
        GET(urlString, parameters: parameters, success: { (_, result) -> Void in
            // 5.5.闭包回调,获得到数据
            let dict = result as? [String: AnyObject]
            finished(result: dict, error: nil)
            }) { (_, error) -> Void in
                // 5.5.闭包回调,出现了错误
                finished(result: nil, error: error)
        }
    }
    
    func loadUserInfo(finished :(result:[String:AnyObject]?,error:NSError?)->()){
        
        guard let access_token = JCUserAccount.loadAccount()?.access_token else {
            let error = JCNetworkError.emptyAccessToken.error()
            finished(result: nil,error: error)
            return
        }
        guard let uid = JCUserAccount.loadAccount()?.uid else {
        
            let error = JCNetworkError.emptyUid.error()
            
            // 告诉调用者,网络请求出错
            finished(result: nil, error: error)
            return
        }
        
        
        let urlString = "2/users/show.json"
        
        let parameters = [
            "access_token": access_token,
            "uid": uid
        ]
        // 5.发送请求获取用户数据
        GET(urlString, parameters: parameters, success: { (_, result) -> Void in
            // 6.调用准备好的闭包
            let dict = result as? [String: AnyObject]
            finished(result: dict, error: nil)
            }) { (_, error) -> Void in
                // 6.调用准备好的闭包
                finished(result: nil, error: error)
        }
        
        
        
    }
}
